<template lang="pug">
  v-container
    CriterionBuilder(ref="criterionBuilder" :bundle="asset" @refresh="refreshCriteria")
    v-card
      v-toolbar(color="purple darken-4" dark dense)
        v-toolbar-title 基本信息
        v-spacer
        v-toolbar-items
          v-btn(text @click="$emit('toggleModel', 'edit')") 编辑
      v-form(ref="form")
        v-container(grid-list-lg)
          v-layout(wrap)
            v-flex(v-for="f in fields" xs12 md12)
              h4.body-2 {{ label(f) }}
              p.body-1.text--primary {{ value(f) }}
    v-card.mt-4
      v-toolbar(color="purple darken-4" dark dense)
        v-toolbar-title 资产筛选器
        v-spacer
        v-toolbar-items
          v-btn(text @click="delCriteria") 删除
          v-btn(text @click="addCriterion") 添加资产筛选器
      v-card-text
        BundleItemsDataTable(ref="itemDataGrid", :bundle="asset")

    AttachmentSection.mt-4(ref="attachments", :id="asset.id" :type="attachableType")
</template>
<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import AssetStockMeta from '../asset_stock/asset_stock_meta'
  import BundleItemsDataTable from './filterable_bundle_criteria_data_table'
  import CriterionBuilder from './filterable_bundle_criterion_builder'
  import {isObject, get} from 'lodash'
  import {mapActions} from 'vuex'
  import {map} from 'lodash'
  import {AxiosResponse} from 'axios'
  import {AttachableType} from '@/store/modules/types/Attachment'
  import AttachmentSection from '@/components/shared/AttachmentSectionInDetailsView.vue'

  export default (Vue as VueConstructor<Vue & {
    $refs: {
      criterionBuilder: CriterionBuilder,
      itemDataGrid: BundleItemsDataTable
    }
  }>).extend({
    props: ['asset'],
    components: { BundleItemsDataTable,CriterionBuilder, AttachmentSection },
    methods: {
      ...AssetStockMeta,
      ...mapActions('filterableBundle', ['delItemByIds']),
      delCriteria() {
        let selected = this.$refs.itemDataGrid.selected
        if (selected.length == 0) {
          return
        }
        this.$confirm({
          body: '确认删除？'
        }).then(() => {
          let ids = map(selected, (item) => item.id)
          this.$loading('删除中...')
          this.delItemByIds({ ids }).then((response: AxiosResponse) => {
            this.refreshCriteria()
          }).finally(this.$loading.close)
        })
      },
      refreshCriteria() {
        this.$refs.itemDataGrid.refresh()
      },
      addCriterion() {
        this.$refs.criterionBuilder.toggle()
      },
      value(key: string): string {
        let _v = this.asset[key]
        if (isObject(_v)) {
          _v = get(_v, 'name', 'N/A')
        }
        _v = null === _v ? 'N/A' : _v
        return _v
      }
    },
    data() {
      return {
        attachableType: AttachableType.FilterableAssetBundle,
        fields: [
          'name', 'description'
        ]
      }
    }
  })
</script>